package com.itheima.stock.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.itheima.stock.common.ResponseCode;
import com.itheima.stock.common.domain.*;
import com.itheima.stock.config.vo.StockInfoConfig;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockBusiness;
import com.itheima.stock.service.StockService;
import com.itheima.stock.utils.DateTimeUtil;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.resp.R;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Service("stockService")
public class StockServiceimpl implements StockService {

    @Autowired
    private StockBusinessMapper businessMapper;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockBlockRtInfoMapper stockBlockRtInfoMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;

    @Override
    public List<StockBusiness> getAllStockBusiness() {
        List<StockBusiness> finAll = businessMapper.finAll();
        return finAll;
    }

    @Override
    public R<List<InnerMarketDomain>> innerIndexAll() {
        //获取国内大盘的id集合
        List<String> innerid = stockInfoConfig.getInner();
        //获取最近最新的股票有效交易日
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //mock测试数据
        date = DateTime.parse("2022-01-03 11:15:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //将获取的java Date传入接口
        List<InnerMarketDomain> list = stockMarketIndexInfoMapper.getMarketInfo(innerid, date);
        //返回查询结果
        return R.ok(list);

    }

    @Override
    public R<List<StockBlockDomain>> sectorAllLimit() {
        List<StockBlockDomain> infos = stockBlockRtInfoMapper.sectorAllLimit();
//        System.out.println(infos);
        if (CollectionUtils.isEmpty(infos)){
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(infos);
    }

    @Override
    public R<List<StockUpdownDomain>> getStockRtInfoLimit() {
        //获取最近最新的股票有效交易时间点
        Date date = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        //mock数据
        date = DateTime.parse("2021-12-30 09:42:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //调用mapper查询方法
        List<StockUpdownDomain> list = stockRtInfoMapper.getStockRtInfoLimit(date);
        //判断集合是否为空
        if (CollectionUtils.isEmpty(list)){
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
        }
        return R.ok(list);
    }

    @Override
    public R<PageResult<StockUpdownDomain>> stockPage(Integer page, Integer pageSize) {
        //设置分页参数
        PageHelper.startPage(page,pageSize);
        //查询
       List<StockUpdownDomain> pages =stockRtInfoMapper.stockPage();
       if (CollectionUtils.isEmpty(pages)){
           return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
       }
       //组装对象
        PageInfo<StockUpdownDomain> info = new PageInfo<>(pages);
       //转成自定义的分页对象
        PageResult<StockUpdownDomain> pageResult = new PageResult<>(info);
        return R.ok(pageResult);
    }

    @Override
    public R<Map> upDownCount() {
        //借助工具类获取交易日的开盘时间和收盘时间
        //获取有效时间点
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(new DateTime());
        //获取开盘时间和收盘时间
        Date opendate = DateTimeUtil.getOpenDate(dateTime).toDate();
        Date closedate = DateTimeUtil.getCloseDate(dateTime).toDate();
        //mock数据
        opendate = DateTime.parse("2021-12-19 09:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        closedate = DateTime.parse("2021-12-19 15:00:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //查询涨停数据统计
       List<Map> upList =  stockRtInfoMapper.getupDownCount(opendate,closedate,1);
        //查询跌停数据统计
        List<Map> downList =  stockRtInfoMapper.getupDownCount(opendate,closedate,0);
        //组装map
        HashMap<String, List> map = new HashMap<>();
        map.put("upList",upList);
        map.put("downList",downList);
        //返回结果
        return R.ok(map);
    }

    @Override
    public void stockExport(HttpServletResponse response, Integer page, Integer pageSize) throws IOException {
//        System.out.println(page+"---------"+pageSize);
        //设置响应数据类型
        response.setContentType("application/vnd.ms-excel");
        //设置响应数据的编码格式
        response.setCharacterEncoding("utf-8");

        //防止中文乱码
        String filename = URLEncoder.encode("stockRT", "UTF-8");
        //设置默认文件名称
        response.setHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");
        //读取导出的数据集合
        PageHelper.startPage(page,pageSize);
        //查询
        List<StockUpdownDomain> pages =stockRtInfoMapper.stockPage();
        if (CollectionUtils.isEmpty(pages)){
            R<String> error = R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());
            //转为json格式
            String s = new Gson().toJson(error);
            response.getWriter().write(s);
            return;
        }
        //转换类型
        List<StockExcelDomain> collect = pages.stream().map(item -> {
            StockExcelDomain stockExcelDomain = new StockExcelDomain();
            BeanUtils.copyProperties(item, stockExcelDomain);
            return stockExcelDomain;
        }).collect(Collectors.toList());
        //数据导出
        EasyExcel.write(response.getOutputStream(),StockExcelDomain.class)
                .sheet("stockInfo")
                .doWrite(collect);
    }

    @Override
    public R<Map> stockTradeVol4InnerMarket() {
        //1.获取最近的股票交易日时间，精确到分钟 T交易日
        DateTime dateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        dateTime = DateTime.parse("2022-01-03 14:40:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date date = dateTime.toDate();
        //对应的开盘时间
        Date openDate = DateTimeUtil.getOpenDate(dateTime).toDate();
        //获取T-1交易日
        DateTime tradingDay = DateTimeUtil.getPreviousTradingDay(dateTime);
        tradingDay = DateTime.parse("2022-01-02 14:40:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date date1 = tradingDay.toDate();
        Date openDate1 = DateTimeUtil.getOpenDate(tradingDay).toDate();
        //获取大盘的id集合
        List<String> inner = stockInfoConfig.getInner();
        //2.获取T日的股票大盘交易量统计数据
       List<Map> date4T = stockMarketIndexInfoMapper.getStockTradeVol(inner,openDate,date);
        //3.获取T-1的数据
        List<Map> date4PreT = stockMarketIndexInfoMapper.getStockTradeVol(inner,openDate1,date1);
        //4.组装数据
        HashMap<String, List> map = new HashMap<>();
        map.put("volList",date4T);
        map.put("yesVolList",date4PreT);

        return R.ok(map);
    }

    @Override
    public R<Map> stockUpDownScopeCount() {
        //获取最新股票交易时间
        DateTime date = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date date1 = date.toDate();
        date1 = DateTime.parse("2021-12-30 09:42:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //统计数据
       List<Map> ingos = stockRtInfoMapper.stockUpDownScopeCount(date1);
       //获取涨幅区间的顺序集合
        List<String> upDownRange = stockInfoConfig.getUpDownRange();
        //stream过滤收集
        List<Map> newmap = upDownRange.stream().map(item -> {
            Optional<Map> optional = ingos.stream().filter(map -> map.get("title").equals(item)).findFirst();
            //判断结果是否为null
            Map tmp = null;
            if (optional.isPresent()) {
                tmp = optional.get();
            } else {
                tmp = new HashMap<>();
                tmp.put("title", item);
                tmp.put("count", 0);
            }
            return tmp;
        }).collect(Collectors.toList());
//        List<Map> newmap = new ArrayList<>();
//        for (String s : upDownRange) {
//            Map map = null;
//            for (Map ingo : ingos) {
//                if (ingo.get("title").equals(s)){
//                    map = ingo;
//                }
//            }
//            if (map == null){
//                map = new HashMap<>();
//                map.put("title",s);
//                map.put("count",0);
//            }
//            newmap.add(map);
//        }
        //组装数据
        HashMap<String, Object> map = new HashMap<>();
        String s = date.toString(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        map.put("time",s);
        map.put("infos",newmap);
        return R.ok(map);
    }

    @Override
    public R<List<Stock4MinuteDomain>> stockScreenTimeSharing(String code) {
        DateTime date4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date openDate = DateTimeUtil.getOpenDate(date4Stock).toDate();
        Date date = date4Stock.toDate();
        openDate =DateTime.parse("2021-12-30 09:32:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        date =DateTime.parse("2021-12-30 14:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       List<Stock4MinuteDomain> list= stockRtInfoMapper.stockScreenTimeSharing(code,openDate,date);

        return R.ok(list);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> getDayKLinData(String code) {
        //获取日期返回
        DateTime lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now());
        Date date = lastDate4Stock.toDate();
        DateTime dateTime = lastDate4Stock.minusDays(20);
        Date date1 = dateTime.toDate();
        date = DateTime.parse("2022-01-07 15:00:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        date1 = DateTime.parse("2022-01-01 09:30:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       List<Stock4EvrDayDomain> list= stockRtInfoMapper.getDayKLinData(code,date,date1);
       if (CollectionUtils.isEmpty(list)){
           list = new ArrayList<>();
       }
        return R.ok(list);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> getDayKLinData2(String code) {
        DateTime endtime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime starttime = endtime.minusDays(20);
        endtime = DateTime.parse("2022-01-05 10:13:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        starttime = DateTime.parse("2021-12-30 09:33:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date end = endtime.toDate();
        Date start = starttime.toDate();
        List<String> chaofenlj = stockRtInfoMapper.chaofenlj(code, end, start);
        List<Stock4EvrDayDomain> list = stockRtInfoMapper.getDayKLinData2(chaofenlj,code);
        if (CollectionUtils.isEmpty(list)){
            list = new ArrayList<>();
        }
        return R.ok(list);
    }
}
